<template>
  <div class="resource-convergence bg-background text-foreground p-4">
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="专家" name="专家">
        <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-sm">
          <QueryForm :model="expertSearch" :formItems="expertFormItems" @search="searchExpert"
            @reset="resetExpertSearch" />
        </div>
        <div class="action-buttons mb-6 flex items-center justify-between">
          <div class="space-x-2">
            <el-button type="primary" @click="openAddDialog('experts')"
              style="width: 75px; height: 30px;">新增</el-button>
            <el-button @click="deleteSelected('experts')" style="width: 75px; height: 30px;">删除</el-button>
            <el-button @click="openImportDialog('experts')" style="width: 75px; height: 30px;">导入</el-button>
            <el-button @click="exportData('experts')" style="width: 75px; height: 30px;">导出</el-button>
          </div>
        </div>
        <div class="bg-card overflow-hidden rounded-lg shadow-sm">
          <el-table ref="tableExpertRef" v-loading="loading" :data="displayedExpertData" style="width: 100%"
            align="center" class="data-table" @selection-change="handleSelectionExpertChange"
            :header-cell-style="headerCellStyle" empty-text="暂无数据" :row-key="rowKey">
            <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" width="55" header-align="center" align="center">
              <template #default="scope">
                {{ startIndexExpert + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="admin_div" label="行政区划" header-align="center" align="center"></el-table-column>
            <el-table-column prop="park_code" label="园区编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="expert_code" label="专家编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="expert_name" label="专家姓名" header-align="center" align="center"></el-table-column>
            <el-table-column prop="gender" label="性别" header-align="center" align="center"></el-table-column>
            <el-table-column prop="birth_date" label="出生年月" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.birth_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="education" label="学历" header-align="center" align="center"></el-table-column>
            <el-table-column prop="major" label="专业" header-align="center" align="center"></el-table-column>
            <el-table-column prop="title" label="职称" header-align="center" align="center"></el-table-column>
            <el-table-column prop="department" label="所属单位" header-align="center" align="center"></el-table-column>
            <el-table-column prop="contact_number" label="联系方式" header-align="center" align="center"></el-table-column>
            <el-table-column prop="email" label="电子邮箱" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editItem('experts', scope.row)" link>编辑</el-button>
                <el-button type="primary" size="small" @click="viewDetails('experts', scope.row)" link>查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
          <div>
            <p class="text-sm text-muted-foreground">
              一共检索到 <span class="font-medium total-num">{{ totalItemsExpert }}</span> 条信息
            </p>
          </div>
          <div class="flex items-center space-x-2">
            <button @click="prevPageExpert" :disabled="currentPageExpert === 1" class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageExpert === 1 }">
              上一页
            </button>
            <span class="text-sm text-muted-foreground">
              {{ currentPageExpert }} / {{ totalPagesExpert }}
            </span>
            <button @click="nextPageExpert" :disabled="currentPageExpert === totalPagesExpert"
              class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageExpert === totalPagesExpert }">
              下一页
            </button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="队伍" name="队伍">
        <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-sm">
          <QueryForm :model="teamsSearch" :formItems="teamsFormItems" @search="searchTeams" @reset="resetTeamsSearch" />
        </div>
        <div class="action-buttons mb-6 flex items-center justify-between">
          <div class="space-x-2">
            <el-button type="primary" @click="openAddDialog('teams')" style="width: 75px; height: 30px;">新增</el-button>
            <el-button @click="deleteSelected('teams')" style="width: 75px; height: 30px;">删除</el-button>
            <el-button @click="openImportDialog('teams')" style="width: 75px; height: 30px;">导入</el-button>
            <el-button @click="exportData('teams')" style="width: 75px; height: 30px;">导出</el-button>
          </div>
        </div>
        <div class="bg-card overflow-hidden rounded-lg shadow-sm">
          <el-table ref="tableTeamsRef" v-loading="loading" :data="displayedTeamsData" style="width: 100%"
            align="center" class="data-table" @selection-change="handleSelectionTeamsChange"
            :header-cell-style="headerCellStyle" empty-text="暂无数据" :row-key="rowKey">
            <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" width="55" header-align="center" align="center">
              <template #default="scope">
                {{ startIndexTeams + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="admin_div" label="行政区划" header-align="center" align="center"></el-table-column>
            <el-table-column prop="park_code" label="园区编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="team_code" label="队伍编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="team_name" label="队伍名称" header-align="center" align="center"></el-table-column>
            <el-table-column prop="team_type" label="队伍分类" header-align="center" align="center"></el-table-column>
            <el-table-column prop="team_date" label="建队日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.team_date) }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="team_level" label="队伍级别" header-align="center" align="center"></el-table-column> -->
            <el-table-column prop="department" label="所属单位" header-align="center" align="center"></el-table-column>
            <el-table-column prop="member_count" label="总人数" header-align="center" align="center"></el-table-column>
            <el-table-column prop="contact_person" label="负责人" header-align="center" align="center"></el-table-column>
            <el-table-column prop="contact_number" label="联系方式" header-align="center" align="center"></el-table-column>
            <el-table-column prop="address" label="地址" header-align="center" align="center"></el-table-column>
            <el-table-column prop="longitude" label="经度" header-align="center" align="center"></el-table-column>
            <el-table-column prop="latitude" label="纬度" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editItem('teams', scope.row)" link>编辑</el-button>
                <el-button type="primary" size="small" @click="viewDetails('teams', scope.row)" link>查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
          <div>
            <p class="text-sm text-muted-foreground">
              一共检索到 <span class="font-medium total-num">{{ totalItemsTeams }}</span> 条信息
            </p>
          </div>
          <div class="flex items-center space-x-2">
            <button @click="prevPageTeams" :disabled="currentPageTeams === 1" class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageTeams === 1 }">
              上一页
            </button>
            <span class="text-sm text-muted-foreground">
              {{ currentPageTeams }} / {{ totalPagesTeams }}
            </span>
            <button @click="nextPageTeams" :disabled="currentPageTeams === totalPagesTeams"
              class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageTeams === totalPagesTeams }">
              下一页
            </button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="物资" name="物资">
        <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-sm">
          <QueryForm :model="materialSearch" :formItems="materialFormItems" @search="searchMaterial"
            @reset="resetMaterialSearch" />
        </div>
        <div class="action-buttons mb-6 flex items-center justify-between">
          <div class="space-x-2">
            <el-button type="primary" @click="openAddDialog('material')"
              style="width: 75px; height: 30px;">新增</el-button>
            <el-button @click="deleteSelected('material')" style="width: 75px; height: 30px;">删除</el-button>
            <el-button @click="openImportDialog('material')" style="width: 75px; height: 30px;">导入</el-button>
            <el-button @click="exportData('material')" style="width: 75px; height: 30px;">导出</el-button>
          </div>
        </div>
        <div class="bg-card overflow-hidden rounded-lg shadow-sm">
          <el-table ref="tableMaterialRef" v-loading="loading" :data="displayedMaterialData" style="width: 100%"
            align="center" class="data-table" @selection-change="handleSelectionMaterialChange"
            :header-cell-style="headerCellStyle" empty-text="暂无数据" :row-key="rowKey">
            <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" width="55" header-align="center" align="center">
              <template #default="scope">
                {{ startIndexMaterial + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="admin_div" label="行政区划" header-align="center" align="center"></el-table-column>
            <el-table-column prop="park_code" label="园区编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="material_code" label="物资编码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="material_name" label="物资名称" header-align="center" align="center"></el-table-column>
            <el-table-column prop="material_type" label="物资分类" header-align="center" align="center"></el-table-column>
            <el-table-column prop="use_tu" label="用途" header-align="center" align="center"></el-table-column>
            <el-table-column prop="requirements" label="存储和运输要求" header-align="center" align="center"></el-table-column>
            <el-table-column prop="department" label="所属单位" header-align="center" align="center"></el-table-column>
            <el-table-column prop="storage_location" label="存放位置" header-align="center"
              align="center"></el-table-column>
            <el-table-column prop="longitude" label="经度" header-align="center" align="center"></el-table-column>
            <el-table-column prop="latitude" label="纬度" header-align="center" align="center"></el-table-column>
            <el-table-column prop="quantity" label="数量" header-align="center" align="center"></el-table-column>
            <el-table-column prop="contact_person" label="负责人" header-align="center" align="center"></el-table-column>
            <el-table-column prop="contact_number" label="联系方式" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editItem('material', scope.row)" link>编辑</el-button>
                <el-button type="primary" size="small" @click="viewDetails('material', scope.row)" link>查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
          <div>
            <p class="text-sm text-muted-foreground">
              一共检索到 <span class="font-medium total-num">{{ totalItemsMaterial }}</span> 条信息
            </p>
          </div>
          <div class="flex items-center space-x-2">
            <button @click="prevPageMaterial" :disabled="currentPageMaterial === 1" class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageMaterial === 1 }">
              上一页
            </button>
            <span class="text-sm text-muted-foreground">
              {{ currentPageMaterial }} / {{ totalPagesMaterial }}
            </span>
            <button @click="nextPageMaterial" :disabled="currentPageMaterial === totalPagesMaterial"
              class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageMaterial === totalPagesMaterial }">
              下一页
            </button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增编辑专家对话框 -->
    <el-dialog class="dialog-from" v-model="isAddExpertDialogOpen"
      :title="isExpertDialogType == 'add' ? '应急专家新增' : '应急专家编辑'" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="formExpertData" label-width="auto" :rules="rulesExpert" ref="formExpertRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="行政区划：" label-position="top" prop="admin_div">
                  <el-input v-model="formExpertData.admin_div" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="园区编码：" label-position="top" prop="park_code">
                  <el-input v-model="formExpertData.park_code" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="专家编码：" label-position="top" prop="expert_code">
                  <el-input v-model="formExpertData.expert_code" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="专家姓名：" label-position="top" prop="expert_name">
                  <el-input v-model="formExpertData.expert_name" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别：" label-position="top" prop="gender">
                  <el-select v-model="formExpertData.gender" placeholder="请选择" clearable>
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="出生日期：" label-position="top" prop="birth_date">
                  <input type="date" v-model="formExpertData.birth_date" required
                    class="input-time mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring">
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="学历：" label-position="top" prop="education">
                  <el-select v-model="formExpertData.education" placeholder="请选择" clearable>
                    <el-option label="大专" value="大专" />
                    <el-option label="本科" value="本科" />
                    <el-option label="硕士" value="硕士" />
                    <el-option label="博士" value="博士" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="专业：" label-position="top" prop="major">
                  <el-select v-model="formExpertData.major" placeholder="请选择" clearable>
                    <el-option label="化学工程与技术" value="化学工程与技术" />
                    <el-option label="安全科学与工程" value="安全科学与工程" />
                    <el-option label="环境科学与工程" value="环境科学与工程" />
                    <el-option label="化学工程与工艺" value="化学工程与工艺" />
                    <el-option label="安全工程" value="安全工程" />
                    <el-option label="环境工程" value="环境工程" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="职称：" label-position="top" prop="title">
                  <el-select v-model="formExpertData.title" placeholder="请选择" clearable>
                    <el-option label="高级工程师" value="高级工程师" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="所属单位：" label-position="top" prop="department">
                  <el-select v-model="formExpertData.department" placeholder="请选择" clearable>
                    <el-option label="陕西侨岭润岳生物科技有限公司" value="陕西侨岭润岳生物科技有限公司" />
                    <el-option label="陕西格丽达生物科技有限公司" value="陕西格丽达生物科技有限公司" />
                    <el-option label="陕西妙龙居新材料科技有限公司" value="陕西妙龙居新材料科技有限公司" />
                    <el-option label="大荔瑞联新材料股份有限责任公司" value="大荔瑞联新材料股份有限责任公司" />
                    <el-option label="大荔海泰新材料有限责任公司" value="大荔海泰新材料有限责任公司" />
                    <el-option label="陕西科谱华生物科技有限公司" value="陕西科谱华生物科技有限公司" />
                    <el-option label="陕西北农华绿色生物技术有限公司" value="陕西北农华绿色生物技术有限公司" />
                    <el-option label="陕西萌益生物科技有限公司" value="陕西萌益生物科技有限公司" />
                    <el-option label="西安益维聚泰新材料科技有限公司" value="西安益维聚泰新材料科技有限公司" />
                    <el-option label="西安德立生物化工有限公司" value="西安德立生物化工有限公司" />
                    <el-option label="陕西同州蔚隆化学科技有限公司" value="陕西同州蔚隆化学科技有限公司" />
                    <el-option label="陕西港华生物科技有限公司" value="陕西港华生物科技有限公司" />
                    <el-option label="陕西迈祥有机玻璃科技有限公司" value="陕西迈祥有机玻璃科技有限公司" />
                    <el-option label="陕西英唐食用新材料科技有限公司" value="陕西英唐食用新材料科技有限公司" />
                    <el-option label="光大绿色环保城乡再生能源（大荔）有限公司" value="光大绿色环保城乡再生能源（大荔）有限公司" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式：" label-position="top" prop="contact_number">
                  <el-input type="number" v-model="formExpertData.contact_number" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电子邮箱：" label-position="top" prop="email">
                  <el-input v-model="formExpertData.email" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleExpertSubmit">确认</el-button>
          <el-button @click="closeExpertDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增编辑队伍对话框 -->
    <el-dialog class="dialog-from" v-model="isAddTeamsDialogOpen"
      :title="isExpertDialogType == 'add' ? '应急队伍新增' : '应急队伍编辑'" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="formTeamsData" label-width="auto" :rules="rulesTeams" ref="formTeamsRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="行政区划：" label-position="top" prop="admin_div">
                  <el-input v-model="formTeamsData.admin_div" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="园区编码：" label-position="top" prop="park_code">
                  <el-input v-model="formTeamsData.park_code" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="队伍编码：" label-position="top" prop="team_code">
                  <el-input v-model="formTeamsData.team_code" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="队伍名称：" label-position="top" prop="team_name">
                  <el-input v-model="formTeamsData.team_name" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="队伍分类：" label-position="top" prop="team_type">
                  <el-select v-model="formTeamsData.team_type" placeholder="请选择" clearable>
                    <el-option label="专业应急救援力量" value="专业应急救援力量" />
                    <el-option label="社会应急力量" value="社会应急力量" />
                    <el-option label="基层应急救援力量" value="基层应急救援力量" />
                    <el-option label="企业队伍" value="企业队伍" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属单位：" label-position="top" prop="department">
                  <el-select v-model="formTeamsData.department" placeholder="请选择" clearable>
                    <el-option label="陕西侨岭润岳生物科技有限公司" value="陕西侨岭润岳生物科技有限公司" />
                    <el-option label="陕西格丽达生物科技有限公司" value="陕西格丽达生物科技有限公司" />
                    <el-option label="陕西妙龙居新材料科技有限公司" value="陕西妙龙居新材料科技有限公司" />
                    <el-option label="大荔瑞联新材料股份有限责任公司" value="大荔瑞联新材料股份有限责任公司" />
                    <el-option label="大荔海泰新材料有限责任公司" value="大荔海泰新材料有限责任公司" />
                    <el-option label="陕西科谱华生物科技有限公司" value="陕西科谱华生物科技有限公司" />
                    <el-option label="陕西北农华绿色生物技术有限公司" value="陕西北农华绿色生物技术有限公司" />
                    <el-option label="陕西萌益生物科技有限公司" value="陕西萌益生物科技有限公司" />
                    <el-option label="西安益维聚泰新材料科技有限公司" value="西安益维聚泰新材料科技有限公司" />
                    <el-option label="西安德立生物化工有限公司" value="西安德立生物化工有限公司" />
                    <el-option label="陕西同州蔚隆化学科技有限公司" value="陕西同州蔚隆化学科技有限公司" />
                    <el-option label="陕西港华生物科技有限公司" value="陕西港华生物科技有限公司" />
                    <el-option label="陕西迈祥有机玻璃科技有限公司" value="陕西迈祥有机玻璃科技有限公司" />
                    <el-option label="陕西英唐食用新材料科技有限公司" value="陕西英唐食用新材料科技有限公司" />
                    <el-option label="光大绿色环保城乡再生能源（大荔）有限公司" value="光大绿色环保城乡再生能源（大荔）有限公司" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="总人数：" label-position="top" prop="member_count">
                  <el-input type="number" v-model="formTeamsData.member_count" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="负责人：" label-position="top" prop="contact_person">
                  <el-input v-model="formTeamsData.contact_person" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式：" label-position="top" prop="contact_number">
                  <el-input type="number" v-model="formTeamsData.contact_number" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="地址：" label-position="top" prop="address">
                  <el-input v-model="formTeamsData.address" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="经度：" label-position="top" prop="longitude">
                  <el-input type="number" @input="updateLongitude" v-model="formTeamsData.longitude"
                    placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="纬度：" label-position="top" prop="latitude">
                  <el-input type="number" @input="updateLatitude" v-model="formTeamsData.latitude" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="建队日期：" label-position="top" prop="team_date">
                  <input type="date" v-model="formTeamsData.team_date"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleTeamsSubmit">确认</el-button>
          <el-button @click="closeTeamsDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增编辑物资对话框 -->
    <el-dialog class="dialog-from" v-model="isAddMaterialDialogOpen"
      :title="isMaterialDialogType == 'add' ? '应急物资新增' : '应急物资编辑'" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="formMaterialData" label-width="auto" :rules="rulesMaterial" ref="formMaterialRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="行政区划：" label-position="top" prop="admin_div">
                  <el-input v-model="formMaterialData.admin_div" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="园区编码：" label-position="top" prop="park_code">
                  <el-input v-model="formMaterialData.park_code" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物资编码：" label-position="top" prop="material_code">
                  <el-input v-model="formMaterialData.material_code" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="物资名称：" label-position="top" prop="material_name">
                  <el-input v-model="formMaterialData.material_name" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物资分类：" label-position="top" prop="material_type">
                  <el-select v-model="formMaterialData.material_type" placeholder="请选择" clearable>
                    <el-option label="生活保障类" value="生活保障类" />
                    <el-option label="生命救助类" value="生命救助类" />
                    <el-option label="基层应急救援力量" value="动力燃料类" />
                    <el-option label="通讯广播类" value="通讯广播类" />
                    <el-option label="污染清理类" value="污染清理类" />
                    <el-option label="个人防护类" value="个人防护类" />
                    <el-option label="工程设备类" value="工程设备类" />
                    <el-option label="医疗救护类" value="医疗救护类" />
                    <el-option label="照明设备类" value="照明设备类" />
                    <el-option label="交通运输类" value="交通运输类" />
                    <el-option label="器材工具类" value="器材工具类" />
                    <el-option label="侦检探测类" value="侦检探测类" />
                    <el-option label="消防灭火类" value="消防灭火类" />
                    <el-option label="生命支持类" value="生命支持类" />
                    <el-option label="其他物资装备" value="其他物资装备" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用途：" label-position="top" prop="use_tu">
                  <el-input v-model="formMaterialData.use_tu" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="存储和运输要求：" label-position="top" prop="requirements">
                  <el-input v-model="formMaterialData.requirements" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属单位：" label-position="top" prop="department">
                  <el-select v-model="formMaterialData.department" placeholder="请选择" clearable>
                    <el-option label="陕西侨岭润岳生物科技有限公司" value="陕西侨岭润岳生物科技有限公司" />
                    <el-option label="陕西格丽达生物科技有限公司" value="陕西格丽达生物科技有限公司" />
                    <el-option label="陕西妙龙居新材料科技有限公司" value="陕西妙龙居新材料科技有限公司" />
                    <el-option label="大荔瑞联新材料股份有限责任公司" value="大荔瑞联新材料股份有限责任公司" />
                    <el-option label="大荔海泰新材料有限责任公司" value="大荔海泰新材料有限责任公司" />
                    <el-option label="陕西科谱华生物科技有限公司" value="陕西科谱华生物科技有限公司" />
                    <el-option label="陕西北农华绿色生物技术有限公司" value="陕西北农华绿色生物技术有限公司" />
                    <el-option label="陕西萌益生物科技有限公司" value="陕西萌益生物科技有限公司" />
                    <el-option label="西安益维聚泰新材料科技有限公司" value="西安益维聚泰新材料科技有限公司" />
                    <el-option label="西安德立生物化工有限公司" value="西安德立生物化工有限公司" />
                    <el-option label="陕西同州蔚隆化学科技有限公司" value="陕西同州蔚隆化学科技有限公司" />
                    <el-option label="陕西港华生物科技有限公司" value="陕西港华生物科技有限公司" />
                    <el-option label="陕西迈祥有机玻璃科技有限公司" value="陕西迈祥有机玻璃科技有限公司" />
                    <el-option label="陕西英唐食用新材料科技有限公司" value="陕西英唐食用新材料科技有限公司" />
                    <el-option label="光大绿色环保城乡再生能源（大荔）有限公司" value="光大绿色环保城乡再生能源（大荔）有限公司" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="存放位置：" label-position="top" prop="storage_location">
                  <el-input v-model="formMaterialData.storage_location" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="经度：" label-position="top" prop="longitude">
                  <el-input type="number" @input="updateLongitudeMaterial" v-model="formMaterialData.longitude"
                    placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="纬度：" label-position="top" prop="latitude">
                  <el-input type="number" @input="updateLatitudeMaterial" v-model="formMaterialData.latitude"
                    placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="数量：" label-position="top" prop="quantity">
                  <el-input type="number" v-model="formMaterialData.quantity" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="负责人：" label-position="top" prop="contact_person">
                  <el-input v-model="formMaterialData.contact_person" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式：" label-position="top" prop="contact_number">
                  <el-input type="number" v-model="formMaterialData.contact_number" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="当前状态：" label-position="top" prop="now_status">
                  <el-select v-model="formMaterialData.now_status" placeholder="请选择" clearable>
                    <el-option label="需检查" value="需检查" />
                    <el-option label="可用" value="可用" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="更新日期：" label-position="top" prop="updated_at">
                  <input type="date" v-model="formMaterialData.updated_at"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleMaterialSubmit">确认</el-button>
          <el-button @click="closeMaterialDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看专家详情对话框 -->
    <el-dialog class="dialog-from" v-model="isViewExpertDialogOpen" title="应急专家详情" width="900" destroy-on-close
      align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-descriptions title="" :column="3">
            <el-descriptions-item label="行政区划：">{{ viewingExpert.admin_div }}</el-descriptions-item>
            <el-descriptions-item label="园区编码：">{{ viewingExpert.park_code }}</el-descriptions-item>
            <el-descriptions-item label="专家编码：">{{ viewingExpert.expert_code }}</el-descriptions-item>
            <el-descriptions-item label="专家姓名：">{{ viewingExpert.expert_name }}</el-descriptions-item>
            <el-descriptions-item label="性别：">{{ viewingExpert.gender }}</el-descriptions-item>
            <el-descriptions-item label="出生日期：">{{ viewingExpert.birth_date }}</el-descriptions-item>
            <el-descriptions-item label="学历：">{{ viewingExpert.education }}</el-descriptions-item>
            <el-descriptions-item label="专业：">{{ viewingExpert.major }}</el-descriptions-item>
            <el-descriptions-item label="职称：">{{ viewingExpert.title }}</el-descriptions-item>
            <el-descriptions-item label="所属单位：">{{ viewingExpert.department }}</el-descriptions-item>
            <el-descriptions-item label="联系方式：">{{ viewingExpert.contact_number }}</el-descriptions-item>
            <el-descriptions-item label="电子邮箱：">{{ viewingExpert.email }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="isViewExpertDialogOpen = false">确认</el-button>
          <el-button @click="isViewExpertDialogOpen = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看队伍详情对话框 -->
    <el-dialog class="dialog-from" v-model="isViewTeamsDialogOpen" title="应急队伍详情" width="900" destroy-on-close
      align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-descriptions title="" :column="3">
            <el-descriptions-item label="行政区划：">{{ viewingTeam.admin_div }}</el-descriptions-item>
            <el-descriptions-item label="园区编码：">{{ viewingTeam.park_code }}</el-descriptions-item>
            <el-descriptions-item label="队伍编码：">{{ viewingTeam.team_code }}</el-descriptions-item>
            <el-descriptions-item label="队伍名称：">{{ viewingTeam.team_name }}</el-descriptions-item>
            <el-descriptions-item label="队伍分类：">{{ viewingTeam.team_type }}</el-descriptions-item>
            <el-descriptions-item label="所属单位：">{{ viewingTeam.department }}</el-descriptions-item>
            <el-descriptions-item label="建队日期：">{{ formatDate(viewingTeam.team_date) }}</el-descriptions-item>
            <el-descriptions-item label="总人数：">{{ viewingTeam.member_count }}</el-descriptions-item>
            <el-descriptions-item label="负责人：">{{ viewingTeam.contact_person }}</el-descriptions-item>
            <el-descriptions-item label="联系方式：">{{ viewingTeam.contact_number }}</el-descriptions-item>
            <el-descriptions-item label="地址：">{{ viewingTeam.address }}</el-descriptions-item>
            <el-descriptions-item label="经度：">{{ viewingTeam.longitude }}</el-descriptions-item>
            <el-descriptions-item label="纬度：">{{ viewingTeam.latitude }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="isViewTeamsDialogOpen = false">确认</el-button>
          <el-button @click="isViewTeamsDialogOpen = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看物资详情对话框 -->
    <el-dialog class="dialog-from" v-model="isViewMaterialDialogOpen" title="应急物资详情" width="900" destroy-on-close
      align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-descriptions title="" :column="3">
            <el-descriptions-item label="行政区划：">{{ viewingMaterial.admin_div }}</el-descriptions-item>
            <el-descriptions-item label="园区编码：">{{ viewingMaterial.park_code }}</el-descriptions-item>
            <el-descriptions-item label="物资编码：">{{ viewingMaterial.material_code }}</el-descriptions-item>
            <el-descriptions-item label="物资名称：">{{ viewingMaterial.material_name }}</el-descriptions-item>
            <el-descriptions-item label="物资分类：">{{ viewingMaterial.material_type }}</el-descriptions-item>
            <el-descriptions-item label="用途：">{{ viewingMaterial.use_tu }}</el-descriptions-item>
            <el-descriptions-item label="存储和运输要求：">{{ viewingMaterial.requirements }}</el-descriptions-item>
            <el-descriptions-item label="所属单位：">{{ viewingMaterial.department }}</el-descriptions-item>
            <el-descriptions-item label="存放位置：">{{ viewingMaterial.storage_location }}</el-descriptions-item>
            <el-descriptions-item label="经度：">{{ viewingMaterial.longitude }}</el-descriptions-item>
            <el-descriptions-item label="纬度：">{{ viewingMaterial.latitude }}</el-descriptions-item>
            <el-descriptions-item label="数量：">{{ viewingMaterial.quantity }}</el-descriptions-item>
            <el-descriptions-item label="负责人：">{{ viewingMaterial.contact_person }}</el-descriptions-item>
            <el-descriptions-item label="联系方式：">{{ viewingMaterial.contact_number }}</el-descriptions-item>
            <el-descriptions-item label="当前状态：">{{ viewingMaterial.now_status }}</el-descriptions-item>
            <el-descriptions-item label="更新日期：">{{ formatDate(viewingMaterial.updated_at) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="isViewMaterialDialogOpen = false">确认</el-button>
          <el-button @click="isViewMaterialDialogOpen = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog class="dialog-from" v-model="isImportDialogOpen" :title="titleImport" width="500" destroy-on-close
      align-center>
      <el-upload class="upload-demo" ref="uploadRef" drag :limit="1" :action="`${apiBaseUrl}/${urlImport}/upload`"
        :on-change="handleFileChange" :on-success="handleUploadSuccess" :on-error="handleUploadError"
        :auto-upload="false" :before-upload="beforeUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只可以上传一个文件且只能上传Excel文件！</div>
      </el-upload>
      <div class="download-text" @click="downloadTemplate(urlImport)">下载模版</div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitUpload">上传</el-button>
          <el-button @click="downloadTemplate">
            下载模板
          </el-button> -->
          <el-button @click="isImportDialogOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitFile">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'

const { proxy } = getCurrentInstance()

// const activeTab = ref('experts')
const activeTab = ref('')
const activeName = ref('专家')
const currentPage = ref(1)
const itemsPerPage = 10

const expertSearch = ref({ expert_code: '', expert_name: '', education: '' })
const teamsSearch = ref({ team_code: '', team_name: '', team_type: '' })
const materialSearch = ref({ material_code: '', material_name: '', material_type: '', department: '' })

const experts = ref([])
const teams = ref([])
const materials = ref([])

const allExpertsSelected = ref(false)
const allTeamsSelected = ref(false)
const allMaterialsSelected = ref(false)

const totalItems = computed(() => {
  switch (activeTab.value) {
    case 'experts': return experts.value.length
    case 'teams': return teams.value.length
    case 'materials': return materials.value.length
    default: return 0
  }
})

const totalPages = computed(() => Math.ceil(totalItems.value / itemsPerPage))

const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/resource-management'
})

// 监听 activeTab 的变化
watch(activeTab, (newTab) => {
  console.log('Active tab changed to:', newTab)
  search(newTab)
})
const search = async (type) => {
  try {
    console.log(`Searching ${type} with:`,
      type === 'experts' ? expertSearch.value :
        type === 'teams' ? teamSearch.value :
          materialSearch.value
    )
    console.log('API URL:', `${apiBaseUrl.value}/${type}/search`)
    const response = await axios.get(`${apiBaseUrl.value}/${type}/search`, {
      params: type === 'experts' ? expertSearch.value :
        type === 'teams' ? teamSearch.value :
          materialSearch.value
    })
    console.log('Search response:', response.data)

    switch (type) {
      case 'experts':
        experts.value = response.data.map(expert => ({ ...expert, selected: false }))
        console.log('Processed experts:', experts.value)
        break
      case 'teams':
        teams.value = response.data.map(team => ({ ...team, selected: false }))
        break
      case 'materials':
        materials.value = response.data.map(material => ({ ...material, selected: false }))
        break
    }
  } catch (error) {
    console.error(`搜索${type}失败:`, error)
    if (error.response) {
      console.error('Error response:', error.response.data)
      console.error('Error status:', error.response.status)
      console.error('Error headers:', error.response.headers)
    } else if (error.request) {
      console.error('Error request:', error.request)
    } else {
      console.error('Error message:', error.message)
    }
    console.error('Error config:', error.config)
    alert(`搜索${type}失败: ` + (error.response?.data?.message || error.message))
  }
}

// const fileList = ref([]);
// const handleUploadSuccess = (response, file) => {
//   ElMessage.success('上传成功!');
//   // 处理上传成功的逻辑
// };
// const handleChange = (uploadFile, uploadFiles) => {
//   console.log('222222', uploadFile, uploadFiles)
//   fileList.value = fileList.value.slice(-3)
// }
// const handleUploadError = (err, file) => {
//   ElMessage.error('上传失败!');
//   // 处理上传失败的逻辑
// };
// const beforeUpload = (file) => {
//   const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
//     file.type === 'application/vnd.ms-excel'
//   if (!isExcel) {
//     ElMessage.error('只能上传Excel文件！')
//     return false
//   }
//   return true
// }

// const handleSuccess = (response) => {
//   uploadStatus.value = {
//     type: 'success',
//     message: '文件上传成功！'
//   }
// }
// const uploadStatus = ref(null)
// const handleError = (error) => {
//   uploadStatus.value = {
//     type: 'error',
//     message: '文件上传失败：' + (error.message || '未知错误')
//   }
// }
// const uploadRef = ref(null)
// const submitUpload = async () => {
//   // upload.submit(); // 提交上传
//   if (uploadStatus.value) {
//     if (uploadStatus.value.type === 'success') {
//       uploadRef.value.submit();
//       // uploadRef.value.clearFiles();
//     }
//   }
// };
const file = ref(null);

const openDialog = () => {
  isImportDialogOpen.value = true;
};

const resetFile = () => {
  file.value = null;
};

const handleFileChange = (fileList) => {
  file.value = fileList;
  // console.log(fileList.file)
};

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    // this.$message.error('上传文件只能是 CSV 格式!');
    console.log('只能上传Excel文件！')
  }
  return isExcel;
};
const uploadRef = ref(null);
const submitFile = async () => {
  if (file.value) {
    // 这里可以添加文件处理逻辑
    // await uploadRef.value.submit();
    // await handleValue();
    // alert('导入成功');
    // isImportDialogOpen.value = false;
    uploadRef.value.submit();
    // 等待文件上传完成并获取响应

    // 调用处理值的方法
    // await handleValue();
    // isImportDialogOpen.value = false;
  } else {
    alert('请先选择文件!')
  }
};
const handleUploadSuccess = (response, file) => {
  alert('导入成功')
  handleValue()
  isImportDialogOpen.value = false;
}
const handleUploadError = (error, file) => {
  alert(JSON.parse(error.message).message || '上传失败')
  isImportDialogOpen.value = false;
}
const handleValue = async () => {
  if (activeName.value == '专家') {
    searchExpert()
  } else if (activeName.value == '队伍') {
    searchTeams()
  } else if (activeName.value == '物资') {
    searchMaterial()
  }

}
const downloadTemplate = async (type) => {
  await axios.get(`${apiBaseUrl.value}/${type}/export`)
};
const handleClick = (tab, event) => {
  if (tab == '专家') {
    // searchdata()
    searchExpert()
  } else if (tab == '队伍') {
    searchTeams()
  } else if (tab == '物资') {
    searchMaterial()
  }
}

const loading = ref(false)
const expertData = ref([])
const teamsData = ref([])
const materialData = ref([])

const currentPageMaterial = ref(1)
const pageSizeMaterial = ref(10)
const totalItemsMaterial = computed(() => materialData.value.length)
const totalPagesMaterial = computed(() => Math.ceil(totalItemsMaterial.value / pageSizeMaterial.value))
const startIndexMaterial = computed(() => (currentPageMaterial.value - 1) * pageSizeMaterial.value)

const currentPageTeams = ref(1)
const pageSizeTeams = ref(10)
const totalItemsTeams = computed(() => teamsData.value.length)
const totalPagesTeams = computed(() => Math.ceil(totalItemsTeams.value / pageSizeTeams.value))
const startIndexTeams = computed(() => (currentPageTeams.value - 1) * pageSizeTeams.value)

const currentPageExpert = ref(1)
const pageSizeExpert = ref(10)
const totalItemsExpert = computed(() => expertData.value.length)
const totalPagesExpert = computed(() => Math.ceil(totalItemsExpert.value / pageSizeExpert.value))
const startIndexExpert = computed(() => (currentPageExpert.value - 1) * pageSizeExpert.value)


const displayedMaterialData = computed(() => {
  const start = (currentPageMaterial.value - 1) * pageSizeMaterial.value
  const end = start + pageSizeMaterial.value
  return materialData.value.slice(start, end)
})

const displayedTeamsData = computed(() => {
  const start = (currentPageTeams.value - 1) * pageSizeTeams.value
  const end = start + pageSizeTeams.value
  return teamsData.value.slice(start, end)
})
const displayedExpertData = computed(() => {
  const start = (currentPageExpert.value - 1) * pageSizeExpert.value
  const end = start + pageSizeExpert.value
  return expertData.value.slice(start, end)
})
const searchExpert = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/experts/search`, {
      params: expertSearch.value,
    })
    currentPageExpert.value = 1
    expertData.value = response.data
    selectedExpertIds.value = []
    loading.value = false
  } catch (error) {
    console.error('获取专家列表失败:', error)
    alert(
      '获取专家列表失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const searchTeams = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/teams/search`, {
      params: teamsSearch.value,
    })
    currentPageTeams.value = 1
    teamsData.value = response.data
    selectedExpertIds.value = []
    loading.value = false
  } catch (error) {
    console.error('获取专家列表失败:', error)
    alert(
      '获取专家列表失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const searchMaterial = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/materials/search`, {
      params: materialSearch.value,
    })
    currentPageMaterial.value = 1
    materialData.value = response.data
    selectedMaterialIds.value = []
    loading.value = false
  } catch (error) {
    console.error('获取物资列表失败:', error)
    alert(
      '获取物资列表失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const formExpertRef = ref(null)
const formTeamsRef = ref(null)
const formMaterialRef = ref(null)
const formExpertData = ref({
  id: null,
  admin_div: '',
  park_code: '',
  expert_code: '',
  expert_name: '',
  gender: '',
  birth_date: '',
  education: '',
  major: '',
  title: '',
  department: '',
  contact_number: '',
  email: '',
})
const formTeamsData = ref({
  id: null,
  admin_div: '',
  park_code: '',
  team_code: '',
  team_name: '',
  team_type: '',
  team_level: '',
  department: '',
  member_count: '',
  contact_person: '',
  contact_number: '',
  address: '',
  longitude: null,
  latitude: null,
  team_date: '',
})
const formMaterialData = ref({
  id: null,
  admin_div: '',
  park_code: '',
  material_code: '',
  material_name: '',
  material_type: '',
  use: '',
  requirements: '',
  department: '',
  storage_location: '',
  longitude: '',
  latitude: '',
  contact_person: '',
  contact_number: ''
})

const rulesMaterial = reactive({
  admin_div: [
    { required: true, message: '请输入行政区划', trigger: 'blur' },
  ],
  park_code: [
    { required: true, message: '请输入园区编码', trigger: 'blur' },
  ],
  material_code: [
    { required: true, message: '请输入物资编码', trigger: 'blur' },
  ],
  material_name: [
    { required: true, message: '请输入物资名称', trigger: 'blur' },
  ],
  material_type: [
    { required: true, message: '请选择物资分类', trigger: 'change' },
  ],
  use_tu: [
    { required: true, message: '请输入用途', trigger: 'blur' },
  ],
  requirements: [
    { required: true, message: '请输入存储和运输要求', trigger: 'blur' },
  ],
  department: [
    { required: true, message: '请选择所属单位', trigger: 'change' },
  ],
  storage_location: [
    { required: true, message: '请输入存放位置', trigger: 'blur' },
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { type: 'number', min: -180, max: 180, message: '经度必须在 -180 到 180 之间', trigger: 'blur' },
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度必须在 -90 到 90 之间', trigger: 'blur' },
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
  ],
  contact_person: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
  ],
  contact_number: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
  ],
  now_status: [
    { required: true, message: '请选择当前状态', trigger: 'change' },
  ],
  updated_at: [
    { required: true, message: '请选择更新日期', trigger: 'change' },
  ],
})
const rulesTeams = reactive({
  admin_div: [
    { required: true, message: '请输入行政区划', trigger: 'blur' },
  ],
  park_code: [
    { required: true, message: '请输入园区编码', trigger: 'blur' },
  ],
  team_code: [
    { required: true, message: '请输入队伍编码', trigger: 'blur' },
  ],
  team_name: [
    { required: true, message: '请输入队伍名称', trigger: 'blur' },
  ],
  team_type: [
    { required: true, message: '请选择队伍分类', trigger: 'change' },
  ],
  department: [
    { required: true, message: '请选择所属单位', trigger: 'change' },
  ],
  member_count: [
    { required: true, message: '请输入总人数', trigger: 'blur' },
  ],
  contact_person: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
  ],
  contact_number: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { type: 'number', min: -180, max: 180, message: '经度必须在 -180 到 180 之间', trigger: 'blur' },
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度必须在 -90 到 90 之间', trigger: 'blur' },
  ],
  team_date: [
    { required: true, message: '请选择建队日期', trigger: 'change' },
  ],
})
const rulesExpert = reactive({
  admin_div: [
    { required: true, message: '请输入行政区划', trigger: 'blur' },
  ],
  park_code: [
    { required: true, message: '请输入园区编码', trigger: 'blur' },
  ],
  expert_code: [
    { required: true, message: '请输入专家编码', trigger: 'blur' },
  ],
  expert_name: [
    { required: true, message: '请输入专家姓名', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  birth_date: [
    { required: true, message: '请选择出生日期', trigger: 'change' },
  ],
  education: [
    { required: true, message: '请选择学历', trigger: 'change' },
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' },
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' },
  ],
  department: [
    { required: true, message: '请选择所属单位', trigger: 'change' },
  ],
  contact_number: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
  ],
})
const resetExpertSearch = () => {
  expertSearch.value = {
    expert_code: '', expert_name: '', education: ''
  }
  searchExpert()
}
const resetTeamsSearch = () => {
  teamsSearch.value = { team_code: '', team_name: '', team_type: '' }
  searchTeams()
}
const resetMaterialSearch = () => {
  materialSearch.value = { material_code: '', material_name: '', material_type: '', department: '' }
  searchMaterial()
}
const resetExpertForm = () => {
  formExpertData.value = {
    id: null,
    admin_div: '',
    park_code: '',
    expert_code: '',
    expert_name: '',
    gender: '',
    birth_date: '',
    education: '',
    major: '',
    title: '',
    department: '',
    contact_number: '',
    email: '',
  }
}
const resetTeamsForm = () => {
  formTeamsData.value = {
    id: null,
    admin_div: '',
    park_code: '',
    team_code: '',
    team_name: '',
    team_type: '',
    team_level: '',
    department: '',
    member_count: '',
    contact_person: '',
    contact_number: '',
    address: '',
    longitude: '',
    latitude: '',
    team_date: '',
  }
}
const resetMaterialForm = () => {
  formMaterialData.value = {
    id: null,
    admin_div: '',
    park_code: '',
    material_code: '',
    material_name: '',
    material_type: '',
    use: '',
    requirements: '',
    department: '',
    storage_location: '',
    longitude: '',
    latitude: '',
    contact_person: '',
    contact_number: ''
  }
}
const handleExpertSubmit = () => {
  try {
    formExpertRef.value.validate(async (valid) => {
      if (valid) {
        if (!formExpertData.value.id) {
          const response = await axios.post(`${apiBaseUrl.value}/experts`, formExpertData.value)
          alert(response.data.message || '新增专家成功')
        } else {
          console.log(formExpertData.value)
          const response = await axios.put(`${apiBaseUrl.value}/experts/${formExpertData.value.id}`, formExpertData.value)
          alert(response.data.message || '编辑专家成功')
        }
        await searchExpert()
        closeExpertDialog()
      }
    })
  } catch (error) {
    console.error('新增专家失败:', error)
    alert(
      '新增专家失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const updateLongitude = (value) => {
  formTeamsData.value.longitude = Number(value); // 转换为数字
}
const updateLatitude = (value) => {
  formTeamsData.value.latitude = Number(value); // 转换为数字
}
const updateLongitudeMaterial = (value) => {
  formMaterialData.value.longitude = Number(value); // 转换为数字
}
const updateLatitudeMaterial = (value) => {
  formMaterialData.value.latitude = Number(value); // 转换为数字
}
const handleTeamsSubmit = () => {
  try {
    formTeamsRef.value.validate(async (valid) => {
      if (valid) {
        if (!formTeamsData.value.id) {
          const response = await axios.post(`${apiBaseUrl.value}/teams`, formTeamsData.value)
          alert(response.data.message || '新增队伍成功')
        } else {
          const response = await axios.put(`${apiBaseUrl.value}/teams/${formTeamsData.value.id}`, formTeamsData.value)
          alert(response.data.message || '编辑队伍成功')
        }
        await searchTeams()
        closeTeamsDialog()
      }
    })
  } catch (error) {
    console.error('新增专家失败:', error)
    alert(
      '新增专家失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const handleMaterialSubmit = () => {
  try {
    formMaterialRef.value.validate(async (valid) => {
      if (valid) {
        if (!formMaterialData.value.id) {
          const response = await axios.post(`${apiBaseUrl.value}/materials`, formMaterialData.value)
          alert(response.data.message || '新增物资成功')
        } else {
          const response = await axios.put(`${apiBaseUrl.value}/materials/${formMaterialData.value.id}`, formMaterialData.value)
          alert(response.data.message || '编辑物资成功')
        }
        await searchMaterial()
        closeMaterialDialog()
      }
    })
  } catch (error) {
    console.error('新增专家失败:', error)
    alert(
      '新增专家失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const selectedExpertIds = ref([])
const selectedTeamsIds = ref([])
const selectedMaterialIds = ref([])
const handleSelectionExpertChange = (selection) => {
  selectedExpertIds.value = selection;
}
const handleSelectionTeamsChange = (selection) => {
  selectedTeamsIds.value = selection;
}
const handleSelectionMaterialChange = (selection) => {
  selectedMaterialIds.value = selection;
}
const expertFormItems = ref([
  {
    label: '专家编码：',
    model: 'expert_code',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '专家姓名：',
    model: 'expert_name',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '学历：',
    model: 'education',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '大专', value: '大专' },
      { label: '本科', value: '本科' },
      { label: '硕士', value: '硕士' },
      { label: '博士', value: '博士' },
      { label: '其他', value: '其他' },
    ],
  },
]);
const materialFormItems = ref([
  {
    label: '物资编码：',
    model: 'material_code',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '物资名称：',
    model: 'material_name',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '物资分类：',
    model: 'material_type',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '生活保障类', value: '生活保障类' },
      { label: '生命救助类', value: '生命救助类' },
      { label: '动力燃料类', value: '动力燃料类' },
      { label: '通讯广播类', value: '通讯广播类' },
      { label: '污染清理类', value: '污染清理类' },
      { label: '个人防护类', value: '个人防护类' },
      { label: '工程设备类', value: '工程设备类' },
      { label: '医疗救护类', value: '医疗救护类' },
      { label: '照明设备类', value: '照明设备类' },
      { label: '交通运输类', value: '交通运输类' },
      { label: '器材工具类', value: '器材工具类' },
      { label: '侦检探测类', value: '侦检探测类' },
      { label: '消防灭火类', value: '消防灭火类' },
      { label: '生命支持类', value: '生命支持类' },
      { label: '其他物资装备', value: '其他物资装备' },
    ],
  },
  {
    label: '所属单位：',
    model: 'department',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '陕西侨岭润岳生物科技有限公司', value: '陕西侨岭润岳生物科技有限公司' },
      { label: '陕西格丽达生物科技有限公司', value: '陕西格丽达生物科技有限公司' },
      { label: '陕西妙龙居新材料科技有限公司', value: '陕西妙龙居新材料科技有限公司' },
      { label: '大荔瑞联新材料股份有限责任公司', value: '大荔瑞联新材料股份有限责任公司' },
      { label: '大荔海泰新材料有限责任公司', value: '大荔海泰新材料有限责任公司' },
      { label: '陕西科谱华生物科技有限公司', value: '陕西科谱华生物科技有限公司' },
      { label: '陕西北农华绿色生物技术有限公司', value: '陕西北农华绿色生物技术有限公司' },
      { label: '陕西萌益生物科技有限公司', value: '陕西萌益生物科技有限公司' },
      { label: '西安益维聚泰新材料科技有限公司', value: '西安益维聚泰新材料科技有限公司' },
      { label: '西安德立生物化工有限公司', value: '西安德立生物化工有限公司' },
      { label: '陕西同州蔚隆化学科技有限公司', value: '陕西同州蔚隆化学科技有限公司' },
      { label: '陕西港华生物科技有限公司', value: '陕西港华生物科技有限公司' },
      { label: '陕西迈祥有机玻璃科技有限公司', value: '陕西迈祥有机玻璃科技有限公司' },
      { label: '陕西英唐食用新材料科技有限公司', value: '陕西英唐食用新材料科技有限公司' },
      { label: '光大绿色环保城乡再生能源（大荔）有限公司', value: '光大绿色环保城乡再生能源（大荔）有限公司' },
    ],
  },
]);
const teamsFormItems = ref([
  {
    label: '队伍编码：',
    model: 'team_code',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '队伍名称：',
    model: 'team_name',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '队伍分类：',
    model: 'team_type',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '专业应急救援力量', value: '专业应急救援力量' },
      { label: '社会应急力量', value: '社会应急力量' },
      { label: '基层应急救援力量', value: '基层应急救援力量' },
      { label: '企业队伍', value: '企业队伍' },
    ],
  },
]);
const prevPageExpert = () => {
  if (currentPageExpert.value > 1) {
    currentPageExpert.value--
  }
}

const nextPageExpert = () => {
  if (currentPageExpert.value < totalPagesExpert.value) {
    currentPageExpert.value++
  }
}
const prevPageTeams = () => {
  if (currentPageTeams.value > 1) {
    currentPageTeams.value--
  }
}

const nextPageTeams = () => {
  if (currentPageTeams.value < totalPagesTeams.value) {
    currentPageTeams.value++
  }
}
const prevPageMaterial = () => {
  if (currentPageMaterial.value > 1) {
    currentPageMaterial.value--
  }
}

const nextPageMaterial = () => {
  if (currentPageMaterial.value < totalPagesMaterial.value) {
    currentPageMaterial.value++
  }
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)

  // 获取年份、月份和日期
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
  const day = String(date.getDate()).padStart(2, '0')

  // 返回格式化后的日期
  return `${year}/${month}/${day}`
}
const resetSearch = (type) => {
  switch (type) {
    case 'experts':
      expertSearch.value = { code: '', name: '', title: '', department: '', major: '', education: '' }
      break
    case 'teams':
      teamsSearch.value = { team_code: '', team_name: '', team_type: '', team_level: '' }
      break
    case 'materials':
      materialSearch.value = { material_code: '', material_name: '', material_type: '', status: '' }
      break
  }
  search(type)
}

const addItem = async (type) => {
  try {
    const newItem = type === 'experts' ? newExpert.value :
      type === 'teams' ? newTeam.value :
        newMaterial.value
    const response = await axios.post(`${apiBaseUrl.value}/${type}`, newItem)
    alert(response.data.message || `创建${type}成功`)
    closeAddDialog()
    await search(type)
  } catch (error) {
    console.error(`创建${type}失败:`, error)
    alert(`创建${type}失败: ` + (error.response?.data?.message || error.message))
  }
}
const formatDateEdit = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const editItem = (type, item) => {
  // console.log("xxx",type, item);
  if (type === 'experts') {
    formExpertData.value = { ...item, birth_date: formatDateEdit(item.birth_date) }
    isExpertDialogType.value = 'edit'
    isAddExpertDialogOpen.value = true
  } else if (type === 'teams') {
    formTeamsData.value = { ...item }
    if (item.team_date) {
      formTeamsData.value.team_date = formatDateEdit(item.team_date)
    }
    isTeamsDialogType.value = 'edit'
    isAddTeamsDialogOpen.value = true
  } else if (type === 'material') {
    formMaterialData.value = { ...item }
    isMaterialDialogType.value = 'edit'
    isAddMaterialDialogOpen.value = true
  }
}

const viewItem = (type, item) => {
  if (type === 'experts') {
    viewingExpert.value = { ...item }
    isViewDialogOpen.value = true
  } else if (type === 'teams') {
    viewingTeam.value = { ...item }
    isViewDialogOpen.value = true
  } else if (type === 'material') {
    viewingMaterial.value = { ...item }
    isViewDialogOpen.value = true
  }
}

const deleteItems = async (type) => {
  const selectedItems = type === 'experts' ? experts.value.filter(e => e.selected) :
    type === 'teams' ? teams.value.filter(t => t.selected) :
      materials.value.filter(m => m.selected)

  if (selectedItems.length === 0) {
    alert('请选择要删除的项目')
    return
  }

  if (confirm(`确定要删除选中的 ${selectedItems.length} 个${type}吗？`)) {
    try {
      await Promise.all(selectedItems.map(item =>
        axios.delete(`${apiBaseUrl.value}/${type}/${item.id}`)
      ))
      alert('删除成功')
      await search(type)
    } catch (error) {
      console.error(`删除${type}失败:`, error)
      alert(`删除${type}失败: ` + (error.response?.data?.message || error.message))
    }
  }
}

const importItems = async (type) => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/${type}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await search(type)
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

const exportItems = (type) => {
  const items = type === 'experts' ? experts.value :
    type === 'teams' ? teams.value :
      materials.value

  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(items)
  XLSX.utils.book_append_sheet(wb, ws, type)
  XLSX.writeFile(wb, `${type}.xlsx`)
}

const toggleAllItems = (type) => {
  switch (type) {
    case 'experts':
      experts.value.forEach(expert => expert.selected = allExpertsSelected.value)
      break
    case 'teams':
      teams.value.forEach(team => team.selected = allTeamsSelected.value)
      break
    case 'materials':
      materials.value.forEach(material => material.selected = allMaterialsSelected.value)
      break
  }
}

const changePage = (page) => {
  currentPage.value = page
  search(activeTab.value)
}

// 初始加载数据
onMounted(() => {
  activeName.value = '专家'
  searchExpert()
})
const rowKey = (row) => row.id;
// 新增的变量
const isAddDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const newExpert = ref({})
const editingExpert = ref({})
const viewingExpert = ref({})
const importFile = ref(null)
const viewingTeam = ref({})
const viewingMaterial = ref({})
const newTeam = ref({})
const editingTeam = ref({})
const newMaterial = ref({})
const editingMaterial = ref({})

// 关闭新增对话框
const closeExpertDialog = () => {
  isAddExpertDialogOpen.value = false
  resetExpertForm()
}
// 关闭新增对话框
const closeTeamsDialog = () => {
  isAddTeamsDialogOpen.value = false
  resetTeamsForm()
}
const closeMaterialDialog = () => {
  isAddMaterialDialogOpen.value = false
  resetMaterialForm()
}
const tableExpertRef = ref(null)
const tableTeamsRef = ref(null)
const tableMaterialRef = ref(null)
// 删除选中的项目
const deleteSelected = async (type) => {
  try {
    if (type == 'experts') {
      if (selectedExpertIds.value.length === 0) {
        alert('请至少选择一条记录进行删除')
        return
      }
      if (!confirm(`确定要删除选中的 ${selectedExpertIds.value.length} 条记录吗？`)) {
        return
      }
      const deletePromises = selectedExpertIds.value.map(item =>
        axios.delete(`${apiBaseUrl.value}/experts/${item.id}`)
      )
      await Promise.all(deletePromises)
      alert('删除成功')
      if (tableExpertRef.value) {
        tableExpertRef.value.clearSelection();
      }
      selectedExpertIds.value = []
      await searchExpert()
      if (currentPageExpert.value > totalPagesExpert.value) {
        currentPageExpert.value = totalPagesExpert.value;
      }

    } else if (type == 'teams') {
      if (selectedTeamsIds.value.length === 0) {
        alert('请至少选择一条记录进行删除')
        return
      }
      if (!confirm(`确定要删除选中的 ${selectedTeamsIds.value.length} 条记录吗？`)) {
        return
      }
      const deletePromises = selectedTeamsIds.value.map(item =>
        axios.delete(`${apiBaseUrl.value}/teams/${item.id}`)
      )
      await Promise.all(deletePromises)
      alert('删除成功')
      if (tableTeamsRef.value) {
        tableTeamsRef.value.clearSelection();
      }
      selectedTeamsIds.value = []
      await searchTeams()
      if (currentPageTeams.value > totalPagesTeams.value) {
        currentPageTeams.value = totalPagesTeams.value;
      }
    } else if (type == 'material') {
      if (selectedMaterialIds.value.length === 0) {
        alert('请至少选择一条记录进行删除')
        return
      }
      if (!confirm(`确定要删除选中的 ${selectedMaterialIds.value.length} 条记录吗？`)) {
        return
      }
      const deletePromises = selectedMaterialIds.value.map(item =>
        axios.delete(`${apiBaseUrl.value}/materials/${item.id}`)
      )
      await Promise.all(deletePromises)
      alert('删除成功')
      if (tableMaterialRef.value) {
        tableMaterialRef.value.clearSelection();
      }
      selectedMaterialIds.value = []
      await searchMaterial()
      if (currentPageMaterial.value > totalPagesMaterial.value) {
        currentPageMaterial.value = totalPagesMaterial.value;
      }
    }

  }
  catch (error) {
    console.error('删除失败:', error)
    alert('删除失败: ' + (error.response?.data?.message || error.message))
  }
}
const titleImport = ref('')
const urlImport = ref('')
// 打开导入对话框
const openImportDialog = (type) => {
  resetFile()
  if (type === 'experts') {
    titleImport.value = '应急专家导入'
    urlImport.value = "experts"
  } else if (type === 'teams') {
    titleImport.value = '应急队伍导入'
    urlImport.value = "teams"
  } else if (type === 'material') {
    titleImport.value = '应急物资导入'
    urlImport.value = "materials"
  }
  isImportDialogOpen.value = true
  // 可以根据需要添加其他逻辑

}

// 关闭导入对话框
const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

// 处理文件上传
const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

// 导入数据
const importData = async (type) => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/${type}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await search(type)
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

// 导出数据
const exportData = (type) => {
  // const items = type === 'experts' ? expertData.value :
  //   type === 'teams' ? teamsData.value :
  //     materialData.value
  let newExpertData = null
  if (type === 'experts') {
    newExpertData = expertData.value.map((item) => ({
      行政区划: item.admin_div,
      园区编码: item.park_code,
      专家编码: item.expert_code,
      专家姓名: item.expert_name,
      性别: item.gender,
      出生年月: formatDateTime(item.birth_date),
      学历: item.education,
      专业: item.major,
      职称: item.title,
      所属单位: item.department,
      联系方式: item.contact_number,
      电子邮箱: item.email,
    }))
  } else if (type === 'teams') {
    newExpertData = teamsData.value.map((item) => ({
      行政区划: item.admin_div,
      园区编码: item.park_code,
      队伍编码: item.team_code,
      队伍名称: item.team_name,
      队伍分类: item.team_type,
      建队日期: formatDateTime(item.team_date),
      队伍级别: item.team_level,
      所属单位: item.department,
      总人数: item.member_count,
      负责人: item.contact_person,
      联系方式: item.contact_number,
      地址: item.address,
      经度: item.longitude,
      纬度: item.latitude,
    }))
  } else if (type === 'material') {
    newExpertData = materialData.value.map((item) => ({
      行政区划: item.admin_div,
      园区编码: item.park_code,
      物资编码: item.material_code,
      物资名称: item.material_name,
      物资分类: item.material_type,
      用途: item.use_tu,
      存储和运输要求: item.requirements,
      所属单位: item.department,
      存放位置: item.storage_location,
      经度: item.longitude,
      纬度: item.latitude,
      数量: item.quantity,
      负责人: item.contact_person,
      联系方式: item.contact_number,
    }))
  }
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(newExpertData)
  XLSX.utils.book_append_sheet(wb, ws, type)
  XLSX.writeFile(wb, `${type}.xlsx`)
}

// 打开编辑对话框
const openEditDialog = (type, item) => {
  if (type === 'experts') {
    isEditDialogOpen.value = true
    editingExpert.value = { ...item }
  } else if (type === 'teams') {
    isEditDialogOpen.value = true
    editingTeam.value = { ...item }
  }
  // 可以为其他类型添加相应的逻辑
}

// 关闭编辑对话框
const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingExpert.value = {}
  editingTeam.value = {}
  editingMaterial.value = {}
}

// 更新专家信息
const updateExpert = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/experts/${editingExpert.value.id}`, editingExpert.value)
    alert(response.data.message || '更新专家成功')
    closeEditDialog()
    await search('experts')
  } catch (error) {
    console.error('更新专家失败:', error)
    alert('更新专家失败: ' + (error.response?.data?.message || error.message))
  }
}

// 更新队伍信息
const updateTeam = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/teams/${editingTeam.value.id}`, editingTeam.value)
    alert(response.data.message || '更新队伍成功')
    closeEditDialog()
    await search('teams')
  } catch (error) {
    console.error('更新队伍失败:', error)
    alert('更新队伍失败: ' + (error.response?.data?.message || error.message))
  }
}

const isViewExpertDialogOpen = ref(false)
const isViewTeamsDialogOpen = ref(false)
const isViewMaterialDialogOpen = ref(false)
// 查看详情
const viewDetails = (type, item) => {
  if (type === 'experts') {
    viewingExpert.value = { ...item }
    isViewExpertDialogOpen.value = true
  } else if (type === 'teams') {
    viewingTeam.value = { ...item }
    isViewTeamsDialogOpen.value = true
  } else if (type === 'material') {
    viewingMaterial.value = { ...item }
    isViewMaterialDialogOpen.value = true
  }
  // 可以为其他类型添加相应的逻辑
}

// 关闭查看对话框
const closeViewDialog = () => {
  isViewExpertDialogOpen.value = false
  isViewTeamsDialogOpen.value = false
  isViewMaterialDialogOpen.value = false
  viewingExpert.value = {}
  viewingTeam.value = {}
  viewingMaterial.value = {}
}

// 添加 formatFieldValue 函数来格式化特定字段的值
const formatFieldValue = (key, value) => {
  if (key === 'birth_date') {
    return formatDate(value)
  }
  return value
}

// 添加 formatDate 函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
}

// 添加 getChineseFieldName 函数
const getChineseFieldName = (key) => {
  const fieldNameMap = {
    expert_code: '专家编码',
    expert_name: '专家姓名',
    gender: '性别',
    birth_date: '出生年月',
    education: '学历',
    major: '专业',
    title: '职称',
    department: '所属单位',
    contact_number: '联系方式',
    email: '电子邮箱',
    team_code: '队伍编码',
    team_name: '队伍名称',
    team_type: '队伍类型',
    team_level: '队伍级别',
    member_count: '人员数量',
    contact_person: '联系人',
    material_code: '物资编码',
    material_name: '物资名称',
    material_type: '物资类型',
    specification: '规格型号',
    quantity: '数量',
    unit: '单位',
    storage_location: '存放位置',
    status: '物资状态'
  }
  return fieldNameMap[key] || key
}
const isExpertDialogType = ref('add')
const isTeamsDialogType = ref('add')
const isMaterialDialogType = ref('add')

const isAddExpertDialogOpen = ref(false)
const isAddTeamsDialogOpen = ref(false)
const isAddMaterialDialogOpen = ref(false)
// 打开新增对话框
const openAddDialog = (type) => {
  if (type === 'experts') {
    resetExpertForm()
    isExpertDialogType.value = 'add'
    isAddExpertDialogOpen.value = true;
  } else if (type === 'teams') {
    resetTeamsForm()
    isTeamsDialogType.value = 'add'
    isAddTeamsDialogOpen.value = true;
  } else if (type === 'material') {
    resetMaterialForm()
    isMaterialDialogType.value = 'add'
    isAddMaterialDialogOpen.value = true;
  }
}


// 添加新队伍
const addNewTeam = async () => {
  try {
    const response = await axios.post(`${apiBaseUrl.value}/teams`, newTeam.value)
    alert(response.data.message || '创建队伍成功')
    closeAddDialog()
    await search('teams')
  } catch (error) {
    console.error('创建队伍失败:', error)
    alert('创建队伍失败: ' + (error.response?.data?.message || error.message))
  }
}

// 添加新物资
const addNewMaterial = async () => {
  try {
    const response = await axios.post(`${apiBaseUrl.value}/materials`, newMaterial.value)
    alert(response.data.message || '创建物资成功')
    closeAddDialog()
    await search('materials')
  } catch (error) {
    console.error('创建物资失败:', error)
    alert('创建物资失败: ' + (error.response?.data?.message || error.message))
  }
}



// 更新项目
const updateItem = async (type) => {
  try {
    let updatingItem
    if (type === 'experts') {
      updatingItem = editingExpert.value
    } else if (type === 'teams') {
      updatingItem = editingTeam.value
    } else if (type === 'materials') {
      updatingItem = editingMaterial.value
    }

    const response = await axios.put(`${apiBaseUrl.value}/${type}/${updatingItem.id}`, updatingItem)
    alert(response.data.message || `更新${type}成功`)
    closeEditDialog()
    await search(type)
  } catch (error) {
    console.error(`更新${type}失败:`, error)
    alert(`更新${type}失败: ` + (error.response?.data?.message || error.message))
  }
}

// 添加新项目
const addNewItem = async (type) => {
  try {
    let newItem
    if (type === 'experts') {
      newItem = newExpert.value
    } else if (type === 'teams') {
      newItem = newTeam.value
    } else if (type === 'materials') {
      newItem = newMaterial.value
    }

    const response = await axios.post(`${apiBaseUrl.value}/${type}`, newItem)
    alert(response.data.message || `创建${type}成功`)
    closeAddDialog()
    await search(type)
  } catch (error) {
    console.error(`创建${type}失败:`, error)
    alert(`创建${type}失败: ` + (error.response?.data?.message || error.message))
  }
}

// 编辑队伍
const editTeam = (team) => {
  console.log(team)
  editingTeam.value = { ...team }
  isEditDialogOpen.value = true
}

// 查看队伍详情
const viewTeamDetails = (team) => {
  viewingTeam.value = { ...team }
  isViewDialogOpen.value = true
}

// 导出队伍数据
const exportTeams = () => {
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(teams.value)
  XLSX.utils.book_append_sheet(wb, ws, 'Teams')
  XLSX.writeFile(wb, 'teams.xlsx')
}
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};

</script>

<style scoped>
.resource-convergence {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-container {
  flex: 1;
  overflow-x: auto;
  overflow-y: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  text-align: center;
  padding: 0.5rem;
  white-space: nowrap;
}

/* 可选：为表格添加一些响应式样式 */
@media (max-width: 768px) {

  .data-table th,
  .data-table td {
    padding: 0.25rem;
    font-size: 0.875rem;
  }
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

.box-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}

.download-text {
  color: #409eff;
  cursor: pointer;
  text-align: center;
}
</style>
